package com.binc.testspring.study.mina.study2;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * FileName: Myclient   mina编写的客户但
 * Autho: binC
 * Date:  2022/3/25 9:33
 */
@Slf4j
public class MyClient {

    static  int port = 9091;
    static String host = "127.0.0.1";
    static IoConnector connector = null;

    public static void main(String[] args) throws IOException {
        try {

            connector = new NioSocketConnector();
            connector.setConnectTimeout(3000);
            //设置编码过滤器
            connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MyProtocolFactory(Charset.forName("GBK"))));

            // 注册自己自定义的业务处置对象
            connector.setHandler(new MyClientHandler());
            connector.getSessionConfig().setReadBufferSize(10);


            // 创建链接  链接远程服务器
            ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));

            connectFuture.awaitUninterruptibly();// 无参数的话，一直阻塞到获取链接

            IoSession session = connectFuture.getSession();

            //自定义协议了，我们发送的东西就要是自定义的协议对象了
            MyProtocolPackage protocolPackage = new MyProtocolPackage((byte)1,"fasong");
            //发送的是对象，经过com.binc.testspring.study.mina.study2.MyProtocolEncoder#encode 转成的字节流
            session.write( protocolPackage);

            session.getConfig().setUseReadOperation(true);
            ReadFuture readFuture = session.read().awaitUninterruptibly();
            System.out.println("............"+readFuture.getMessage()+"....");
            //等待关闭链接    // binc_read 这里不是很理解 为什么不自己关闭呢
            session.getCloseFuture().awaitUninterruptibly();

            // 关闭链接
            connector.dispose();

        } catch (Exception e) {
            e.printStackTrace();
        }






    }


}
